package com.lanou.dllo.baisibudejie.activity;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.lanou.dllo.baisibudejie.R;
import com.lanou.dllo.baisibudejie.volley.DiskCache;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;

import static android.R.color.holo_red_dark;

/**
 * Created by dllo on 15/11/5.
 */
public class SendVoiceActivity extends Activity implements View.OnClickListener {
    private Bitmap bitmap;
    private EditText sendVoice_contentEt;
    private TextView sendVoice_cancelTv, sendVoice_sendTv, voiceTv;
    private Button sendVoice_recordingBtn;
    private MediaRecorder mediaRecorder;
    private File myRecAudioFile;
    private boolean sdCardExit;
    private File myRecAudioDir;// 得到Sd卡path
    private ArrayList<String> recordFiles;
    private Uri uri;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //设置布局
        setContentView(R.layout.activity_sendvoice);

        Intent intent = new Intent();
                /* 开启Pictures画面Type设定为image */
        intent.setType("image/*");
                /* 使用Intent.ACTION_GET_CONTENT这个Action */
        intent.setAction(Intent.ACTION_GET_CONTENT);
                /* 取得相片后返回本画面 */
        startActivityForResult(intent, 1);
        initView();//初始化控件
    }

    //初始化控件
    private void initView() {

        sendVoice_contentEt = (EditText) findViewById(R.id.sendVoice_contentEt);//内容
        sendVoice_cancelTv = (TextView) findViewById(R.id.sendVoice_cancelTv);//返回
        sendVoice_cancelTv.setOnClickListener(this);
        sendVoice_sendTv = (TextView) findViewById(R.id.sendVoice_sendTv);//发送
        sendVoice_sendTv.setOnClickListener(this);
        sendVoice_recordingBtn = (Button) findViewById(R.id.sendVoice_recordingBtn);//录音
        ButtonListener buttonListener = new ButtonListener();
        sendVoice_recordingBtn.setOnClickListener(buttonListener);
        sendVoice_recordingBtn.setOnTouchListener(buttonListener);
        sendVoice_recordingBtn.setText("按住录音");
        sendVoice_recordingBtn.setBackgroundResource(android.R.color.holo_red_light);
        voiceTv = (TextView) findViewById(R.id.voiceTv);//录音名
        voiceTv.setOnClickListener(this);
        /* 判断SD Card是否插入 */
        sdCardExit = Environment.getExternalStorageState().equals(
                android.os.Environment.MEDIA_MOUNTED);

        /* 取得SD Card路径作为录音的文件位置 */
        if (sdCardExit) {
            myRecAudioDir = Environment.getExternalStorageDirectory();
        }
        /* 取得SD Card目录里的所有.amr文件 */
        getRecordFiles();

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            uri = data.getData();
            Log.e("uri", uri.toString());
            ContentResolver cr = this.getContentResolver();
            try {
//                BitmapFactory.Options opts = new BitmapFactory.Options();
//                opts.inSampleSize = 4;
//                bitmap = BitmapFactory.decodeStream(cr.openInputStream(uri), null, opts);
                bitmap = BitmapFactory.decodeStream(cr.openInputStream(uri));
                DiskCache cache = new DiskCache();
                cache.putBitmap(uri + "", bitmap);//讲图片存储到本地
                ImageView imageView = (ImageView) findViewById(R.id.sendVoiceIv);
                /* 将Bitmap设定到ImageView */
                imageView.setImageBitmap(bitmap);
            } catch (FileNotFoundException e) {
                Log.e("Exception", e.getMessage(), e);
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.sendVoice_cancelTv://返回
                finish();
                break;
            case R.id.sendVoice_sendTv://发送
                String content = sendVoice_contentEt.getText().toString();

                Intent intent_send = new Intent(this, MyCardActivity.class);
                intent_send.putExtra("text", content);
                intent_send.putExtra("bitmap", uri + "");
                intent_send.putExtra("isVoice", true);
                startActivity(intent_send);
                finish();
                break;

            case R.id.voiceTv://点击播放录音

                openFile(myRecAudioFile);

                break;
        }
    }

    class ButtonListener implements View.OnClickListener, View.OnTouchListener {
        @Override
        public void onClick(View v) {
            if (v.getId() == R.id.sendVoice_recordingBtn) {

            }
        }

        @Override
        public boolean onTouch(View v, MotionEvent event) {

            if (v.getId() == R.id.sendVoice_recordingBtn) {
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    sendVoice_recordingBtn.setText("按住录音");
                    sendVoice_recordingBtn.setBackgroundResource(android.R.color.holo_red_light);

                    if (myRecAudioFile != null) {
                    /* 停止录音 */
                        mediaRecorder.stop();
                        mediaRecorder.release();
                        mediaRecorder = null;
                    }
                    voiceTv.setText("停止：" + myRecAudioFile.getName());
                }
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    sendVoice_recordingBtn.setText("松手结束");
                    sendVoice_recordingBtn.setBackgroundResource(android.R.color.holo_red_dark);
                    if (myRecAudioFile != null) {
                    /* 停止录音 */
                        myRecAudioFile = null;
                    }
                    try {
                        initializeAudio();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

            return false;


        }

        private void initializeAudio() throws IOException {
            {
                try {
                    if (!sdCardExit) {
                        Toast.makeText(SendVoiceActivity.this, "请插入SD Card", Toast.LENGTH_LONG).show();
                        return;
                    }
                    //创建录音频文件
                    // myRecAudioFile = File.createTempFile(strTempFile, ".amr",
                    // myRecAudioDir);
                    File sdcardDir = Environment.getExternalStorageDirectory();
                    String path = sdcardDir.getParent() + sdcardDir.getName();
                    String filePath = path + java.io.File.separator + "Demo";
                    //创建文件，使用自己指定文件名(这里我手动创建好了,我们也可以利用mkdirs的方法来创建)
                    myRecAudioFile = new File("/storage/emulated/0", "new.amr");
                    mediaRecorder = new MediaRecorder();
                    /* 设置录音来源为麦克风 */
                    mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
                    mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
                    mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
                    //文件保存位置
                    mediaRecorder.setOutputFile(myRecAudioFile.getAbsolutePath());
                    mediaRecorder.prepare();
                    mediaRecorder.start();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

        }

    }

    private String getMIMEType(File f) {
        String end = f.getName().substring(f.getName().lastIndexOf(".") + 1,
                f.getName().length()).toLowerCase();
        String type = "";
        if (end.equals("mp3") || end.equals("aac") || end.equals("aac")
                || end.equals("amr") || end.equals("mpeg")
                || end.equals("mp4")) {
            type = "audio";
        } else if (end.equals("jpg") || end.equals("gif") || end.equals("png") || end.equals("jpeg")) {
            type = "image";
        } else {
            type = "*";
        }
        type += "/*";
        return type;
    }

    /* 打开播放录音文件的程序 */
    private void openFile(File f) {
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(android.content.Intent.ACTION_VIEW);
        String type = getMIMEType(f);
        intent.setDataAndType(Uri.fromFile(f), type);
        startActivity(intent);
    }

    // 存储一个音频文件数组到list当中
    private void getRecordFiles() {
        recordFiles = new ArrayList<String>();
        if (sdCardExit) {
            File files[] = myRecAudioDir.listFiles();
            if (files != null) {
                for (int i = 0; i < files.length; i++) {
                    if (files[i].getName().indexOf(".") >= 0) {
                        /* 只取.amr文件 */
                        String fileS = files[i].getName().substring(files[i].getName().indexOf("."));
                        if (fileS.toLowerCase().equals(".amr"))
                            recordFiles.add(files[i].getName());
                    }
                }
            }
        }
    }


}
